package com.zcsy.manage.web.property;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zcsy.commons.constants.Constants;
import com.zcsy.commons.constants.OwnerConstants;
import com.zcsy.commons.model.RequestConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.commons.unique.UniqueNumberUtils;
import com.zcsy.commons.util.DateUtils;
import com.zcsy.manage.model.base.CellHouse;
import com.zcsy.manage.model.base.CellInfo;
import com.zcsy.manage.model.property.CarBill;
import com.zcsy.manage.model.property.CarBillDetail;
import com.zcsy.manage.model.property.FeeBillDetail;
import com.zcsy.manage.model.system.Menu;
import com.zcsy.manage.model.system.User;
import com.zcsy.manage.persistence.weixin.StringUtil;
import com.zcsy.manage.service.base.ICellHouseService;
import com.zcsy.manage.service.base.ICellInfoService;
import com.zcsy.manage.service.property.ICarBillDetailService;
import com.zcsy.manage.service.property.ICarBillService;
import com.zcsy.manage.service.property.IFeeBillDetailService;
import com.zcsy.manage.service.system.IMenuService;

/**
 * @author luoyz
 * @Description: 停车费
 */
@Controller
@RequestMapping(value = "carBill")
public class CarBillController {

    @Autowired
    private ICellHouseService cellHouseService;

    @Autowired
    private ICarBillService carBillService;

    @Autowired
    private ICarBillDetailService carBillDetailService;

    @Autowired
    private IMenuService menuService;

    @Autowired
    private ICellInfoService cellInfoService;
    
    @Autowired
    private IFeeBillDetailService feeBillDetailService;

    private final static int generatedByOwner = 2;

    private CarBill carBill; 
    
    
    
    /**
     * @Method: getCarNoByHouse
     * @Description 通过房屋查找车辆 账单信息
     * @param houseId 房屋id
     * @param payCarBill 当从物业首页进入时应加载页面
     * @return property_car_bill.car_no, house_id
     * @see
     */
    @RequestMapping(value = "getCarManage", method = RequestMethod.GET)
    public String getCarManage(Model model, HttpServletRequest req, HttpServletResponse resp, String houseId, Integer payCarBill) {

        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();

        List<CellHouse> cellHouses = cellHouseService.getListByOwnerIdAndState(ownerId,OwnerConstants.NORMAL_HOUSE_STATE);

        CarBill record = new CarBill();
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId();
        
        record.setCellId(cellId);
        record.setOwnerId(ownerId);
        record.setState(Constants.STATE_ENABLED);
        
        List<CarBill> carBills = carBillService.selectCarByCellId(record);

        for (int i = 0; i < cellHouses.size(); i++) {
            List<CarBill> list = new ArrayList<>();
            for (CarBill car : carBills) {
                if (cellHouses.get(i).getId().equals(car.getHouseId())) {
                    list.add(car);
                }
            }
            cellHouses.get(i).setCarList(list);
        }

        for (int i = 0; i < cellHouses.size(); i++) {
            if (cellHouses.get(i).getCarList().size() == 0) {
                cellHouses.remove(i);
            }
        }
        
        checkingPropertyRightByCellId(req,model);
        checkingCarRightByCellId(req,model); 
        
        model.addAttribute("cellHouses", cellHouses);
        model.addAttribute("user", user);
        model.addAttribute("payCarBill", payCarBill);
        return "property/feebill/carManage";
    }
    
    /**
     * @Description:停车费-我要缴费，获取起始时间
     * @param houseId 房屋id
     * @param carBillId 账单id
     * @return 停车费-我要缴费页面，显示起始时间
     * @author huangls 1449700087@qq.com
     * @date 2016年8月17日
     */
    @RequestMapping(value = "getStartDate", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getStartDate(Model model, String houseId, String carNo, Integer months, HttpServletRequest req ) {
        
        RequestJson result = new RequestJson();
        try {
            // 调用接口查询缴费时间
            String endTime = "";
//          SoapParamsVO vo = InvokeHkWebserviceApi.requestInteface(InvokeHkWebserviceApi.METHOD_NAME_VEHICLE, carNo);
//          if(!vo.isSuccess()) {
//              result.setSuccess(false);
//              result.setMsg(vo.getErrorMessage());
//              return result;
//          } else {
//              endTime = vo.getExpirationTime();
//          }
            
         // 查询缴费单价
            BigDecimal price = BigDecimal.ZERO;
//            vo = InvokeHkWebserviceApi.requestInteface(InvokeHkWebserviceApi.METHOD_NAME_PRICE, carNo);
//            if(!vo.isSuccess()) {
//                result.setSuccess(false);
//                result.setMsg(vo.getErrorMessage());
//                return result;
//            } else {
//                price = new BigDecimal(vo.getPrice()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//            }
            if(StringUtil.isEmptyString(endTime)) {
                endTime = DateUtils.formatDate();
            }
            if(BigDecimal.ZERO == price) {
                price = new BigDecimal(200);
            }
            Date startDate = DateUtils.calDate(DateUtils.stringToDate(endTime), 1);
            Date endDate = DateUtils.calMonthDate(startDate, months);
            
            CarBillDetail detail = new CarBillDetail();
            detail.setMemo(DateUtils.date2Str(startDate, DateUtils.date_sdf) + "-" + DateUtils.date2Str(endDate, DateUtils.date_sdf));
            detail.setUnitPrice(price);
            result.setObj(detail);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("系统异常");
        }
        return result;
    }
    
    /**
     * @Description:根据房屋Id查询车辆账单
     * @param houseId 房屋id
     * @return 停车费-我要缴费页面
     * @author huangls 1449700087@qq.com
     * @date 2016年8月17日
     */
    @RequestMapping(value = "getCarBillListByHouseId", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCarBillListByHouseId(Model model, HttpServletRequest req, String houseId) {
        
        RequestJson result = new RequestJson();
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String ownerId = user.getId();
        try {
            List<CarBill> calBillList = carBillService.selectCarListByOwnerAndHouser(ownerId, houseId);
            result.setObj(calBillList);
            result.setSuccess(true);
        } catch (Exception e) {
            result.setSuccess(false);
        }
        
        return result;
    }

    /**
     * @Description 查询业主所有房屋
     * @param model
     * @param req
     * @param resp
     * @param houseId
     * @return
     */
    @RequestMapping(value = "getHousePayBill", method = RequestMethod.GET)
    public String getHousePayBill(Model model, String houseId, String carBillId, HttpServletRequest req, HttpServletResponse resp) {

        String cellId = ((CellInfo) req.getSession().getAttribute(RequestConstants.OWNER_CELL_INFO)).getId();
        User user = (User) req.getSession().getAttribute(
                RequestConstants.USER_SESSION_ID);
        String userID = user.getId();

        // 获取业主房屋信息
        List<CellHouse> houses = cellHouseService.selectHouseInfoCarBillByOwnerIdCellIdState(userID, OwnerConstants.NORMAL_HOUSE_STATE, cellId);
        for (CellHouse cellHouse : houses) {
            cellHouse.setFullName(cellHouse.getCellName()
                    + cellHouse.getRegionName() + cellHouse.getBuildingName()
                    + cellHouse.getUnitName() + cellHouse.getName());
        }
        
        
        model.addAttribute("houses", houses);
        model.addAttribute("houseId", houseId);
        model.addAttribute("carBillId", carBillId);

        return "property/feebill/payCarBill";
    }

    /**
     * @Method: getCarNoByHouse
     * @Description 我要缴费根据房屋查车牌
     * @param houseId
     *            房屋id
     * @see
     */
    @RequestMapping(value = "getCarNoPayBill", method = RequestMethod.GET)
    public String getCarNoPayBill(Model model, HttpServletRequest req,
            HttpServletResponse resp, String houseId) {

        List<CarBill> carBill = carBillService
                .selectCarBillByOneHouseId(houseId);
        model.addAttribute("carBill", carBill);
        return "property/feebill/payCarBill";
    }

    /**
     * @Description 停车费-车辆管理
     * @param model
     * @param req
     * @param resp
     * @return
     */
    @RequestMapping(value = "getCarManageen", method = RequestMethod.GET)
    public String getCarManageen(Model model, HttpServletRequest req, HttpServletResponse resp) {
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String userID = user.getId();

        // 获取业主房屋信息
        List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(userID, OwnerConstants.NORMAL_HOUSE_STATE);

        // 获取房屋id的集合
        List<String> housesID = new ArrayList<String>();
        Iterator<CellHouse> iterator = houses.iterator();
        while (iterator.hasNext()) {
            CellHouse house = (CellHouse) iterator.next();
            housesID.add(house.getId());
        }
        
        return "property/feebill/carManage";
    }

    /**
     * @Method: overdueCarBill
     * @Description 停车费缴费我的账单列表接口（每个车辆只有一条最近缴费记录）
     * @param token
     * @return houseFullName String 房屋全名 owingMoney String 欠费金额 carID String 账单号
     *         startDate date 起始时间 endDate date 结束时间 carNo String 车牌号
     * @see
     */
    @RequestMapping(value = "carBillRemind", method = RequestMethod.GET)
    public String carBillRemind(Model model, HttpServletRequest req,
            HttpServletResponse resp) {

        User user = (User) req.getSession().getAttribute(
                RequestConstants.USER_SESSION_ID);
        String userID = user.getId();

        // 获取业主房屋信息
        List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
                userID, OwnerConstants.NORMAL_HOUSE_STATE);

        // 获取房屋id的集合
        List<String> housesID = new ArrayList<String>();
        Iterator<CellHouse> iterator = houses.iterator();
        while (iterator.hasNext()) {
            CellHouse house = (CellHouse) iterator.next();
            housesID.add(house.getId());
        }
        // 根据房屋id查询一条最近缴费记录
        List<CarBillDetail> carBillDetail = carBillDetailService
                .selectCarBillDetailByHouseId(housesID);

        if (carBillDetail != null && carBillDetail.size() > 0) {
            // 写入房屋的名称
            Iterator<CarBillDetail> iteratorCarBill = carBillDetail.iterator();
            while (iteratorCarBill.hasNext()) {
                CarBillDetail detail = (CarBillDetail) iteratorCarBill.next();
                if (detail.getName() != null) {
                    detail.setHouseFullName(detail.getCellName()
                            + detail.getRegionName() + detail.getBuildingName()
                            + detail.getUnitName() + detail.getName());
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                String endDateString = formatter.format(detail.getEndDate());
                detail.setEndDateString(endDateString);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String c = sdf.format(detail.getEndDate());
                int endDay = Integer.parseInt(c);
                Date d = new Date();
                int nowDay = Integer.parseInt(sdf.format(d));
                if (nowDay < endDay) {
                    detail.setRestDay("还有" + (endDay - nowDay) + "天到期");
                } else {
                    detail.setRestDay("已到期");
                }
            }
        }
        model.addAttribute("carBillDetail", carBillDetail);
        return "property/feebill/carBillRemind";
    }

    /**
     * @Method: carBindHouse
     * @Description 车牌绑定房屋
     * @param token
     * @param houseId
     *            房屋id
     * @param carNo
     *            车牌
     * @param carType
     *            车辆类型 1-小型车 2-大型车 0-其他
     * @param cellId
     *            小区id
     * @return
     * @see
     */
    @RequestMapping(value = "carBindHouse", method = RequestMethod.GET)
    public RequestJson carBindHouse(Model model, HttpServletRequest req,
            HttpServletResponse resp, String houseId, String carNo,
            Integer carType, String cellId) {

        RequestJson result = new RequestJson();

        // 根据车牌号查询是否绑定了房屋
        CarBill carBill = carBillService.selectByBindingCarNo(carNo);
        // 如果未绑定房屋
        if (carBill == null) {
            CarBill carBillUnbunding = carBillService.selectByUnbundingCarNo(carNo);
            CarBill record = new CarBill();
            record.setId(UniqueNumberUtils.get18UniqueNumber());
            record.setCellId(cellId);
            record.setHouseId(houseId);
            record.setCarNo(carNo);

            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String userID = user.getId();
            record.setOwnerId(userID);
            record.setCarType(carType);
            record.setGenerateWay(OwnerConstants.OPERATOR_TYPE_OWNER);
            record.setUserAccount(user.getLoginname());
            record.setSendTime(DateUtils.gettimestamp());
            record.setState(OwnerConstants.CAR_NUMBER_BOUND);

            // 如果以前解绑过该房屋
            if (carBillUnbunding != null
                    && carBillUnbunding.getBuildingId() == houseId) {
                carBillService.updateBindingState(carBillUnbunding.getId());
                result.setObj(record);
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("成功重绑该车辆");

                // 如果以前车辆解绑过其他房屋或未绑定房屋
            } else {
                carBillService.insert(record);
                result.setObj(record);
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("成功绑定车辆");
            }
            // 如果已绑定此房屋
        } else if (carBill != null && carBill.getBuildingId() == houseId) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            result.setMsg("已绑定此车辆");

        } else {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
            result.setMsg("此车辆已绑定其他房屋");
        }
        return result;
    }

    /**
     * @Method: getCarList
     * @Description 显示车辆列表
     * @param token
     * @return result 房屋及对应车辆信息
     * @see
     */
    @RequestMapping(value = "getCarList", method = RequestMethod.GET)
    public RequestJson getCarList(Model model, HttpServletRequest req,
            HttpServletResponse resp) {

        RequestJson result = new RequestJson();
        try {

            User user = (User) req.getSession().getAttribute(
                    RequestConstants.USER_SESSION_ID);
            String ownerId = user.getId();
            
            // 通过业主id查询房屋地址信息及车牌
            List<CellHouse> record = cellHouseService
                    .selectHouseInfoAndCarNoByOwnerId(ownerId);
            if (!record.isEmpty()) {
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("获取信息成功！");
                result.setObj(record);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("获取信息失败！");
            }

        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.RESULT_EXCEPTION_FALSE);
            result.setMsg("网络异常！");
        }
        return result;
    }

    /**
     * @Method: getCarBillRecord
     * @Description 停车费缴费-缴费记录列表
     * @param pNo
     * @param token
     * @return orderNum String 缴费单号 totalAmount double 缴费总额 ownerHouse String 房屋
     *         carNo String 车牌 period String 缴费时间段 paymentStatus int 缴费状态
     * @throws RuntimeException
     * @see
     */
    @RequestMapping(value = "getCarBillRecord", method = RequestMethod.GET)
    public String getCarBillRecord(Model model, HttpServletRequest req,
            HttpServletResponse resp) throws RuntimeException {

        // 缴费信息
        List<CarBillDetail> carBillList = null;

        User user = (User) req.getSession().getAttribute(
                RequestConstants.USER_SESSION_ID);
        String userID = user.getId();

//        // 获取业主房屋信息
//        List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(
//                userID, OwnerConstants.NORMAL_HOUSE_STATE);
//
//        // 获取房屋id的集合
//        List<String> housesID = new ArrayList<String>();
//        Iterator<CellHouse> iterator = houses.iterator();
//        while (iterator.hasNext()) {
//            CellHouse house = (CellHouse) iterator.next();
//            housesID.add(house.getId());
//        }

        carBillList = carBillService.selectCarBillByHouseId(userID);

        // 写入房屋的名称
        Iterator<CarBillDetail> iteratorCarBillList = carBillList.iterator();
        while (iteratorCarBillList.hasNext()) {
            CarBillDetail detail = (CarBillDetail) iteratorCarBillList.next();
            detail.setHouseFullName(detail.getCellName()
                    + detail.getRegionName() + detail.getBuildingName()
                    + detail.getUnitName() + detail.getName());
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
            if (detail.getStartDate() != null) {
                String startDateString = formatter
                        .format(detail.getStartDate());
                detail.setStartDateString(startDateString);
            }
            if (detail.getEndDate() != null) {
                String endDateString = formatter.format(detail.getEndDate());
                detail.setEndDateString(endDateString);
            }
            detail.setPayStateString(Constants.getPayState(detail.getState()));
        }
        model.addAttribute("carBillList", carBillList);
        return "property/feebill/carBillRecord";
    }

    /**
     * @Method: parkingfeeDetail
     * @Description 停车费账单详情
     * @param carID 停 车账单id
     * @param token
     * @return payTime String 缴费时间 totalAmount double 合计金额 carID String 停车账单id
     *         carNo String 车牌号 ownerHouse String 房屋 startDate String 起始时间
     *         endDate String 结束时间 unitPrice double 停车费单价 paymentStatus bool
     *         缴费状态 paymentType int 缴费方式 operator String 操作人
     * @throws RuntimeException
     * @see
     */
    @RequestMapping(value = "parkingFeeDetail", method = RequestMethod.GET)
    public String parkingFeeDetail(String carID, Model model,
            HttpServletRequest req, HttpServletResponse resp)
            throws RuntimeException {
        // 根据汽车账单id查询账单详情
        /**
         * modified by hubing 20160831 start 
         * reason: 停车费账号号为详情表id号，查询详情直接根据id查询
         */
//        CarBillDetail carBillDetail = carBillDetailService.selectBycarID(carID);
        CarBillDetail carBillDetail = carBillDetailService.selectByPrimaryKey(carID);
        // modified by hubing 20160831 end

        if (carBillDetail != null) {
            // 根据车牌号查询房屋信息
            CarBill carBill = carBillService.selectByPrimaryKey(carBillDetail.getCarId());
            String houseID = carBill.getHouseId();
            CellHouse cellHouse = cellHouseService.selectByPrimaryKey(houseID);
            // 写入房屋的名称
            if (cellHouse != null) {
                carBillDetail.setHouseFullName(cellHouse.getCellName()
                        + cellHouse.getRegionName()
                        + cellHouse.getBuildingName() + cellHouse.getUnitName()
                        + cellHouse.getName());
                Integer state = carBillDetail.getState();
                carBillDetail.setPayStateString(Constants.getPayState(state));
                
                Integer payWay = carBillDetail.getPayWay();
                carBillDetail.setPayWayString(Constants.getPayWay(payWay));
                
                SimpleDateFormat formatterPay = new SimpleDateFormat(
                        "yyyy.MM.dd hh:mm:ss");
                if (carBillDetail.getPayTime() != null) {
                    String payTimeString = formatterPay
                            .format(carBillDetail.getPayTime());
                    carBillDetail.setPayTimeString(payTimeString);
                } else {
                    carBillDetail.setPayTimeString("");
                }
                SimpleDateFormat formatter = new SimpleDateFormat("yyyy.MM.dd");
                if (carBillDetail.getStartDate() != null) {
                    String startDateString = formatter.format(carBillDetail
                            .getStartDate());
                    carBillDetail.setStartDateString(startDateString);
                }
                if (carBillDetail.getEndDate() != null) {
                    String endDateString = formatter.format(carBillDetail
                            .getEndDate());
                    carBillDetail.setEndDateString(endDateString);
                }
            }
        }
        model.addAttribute("carBillDetail", carBillDetail);
        return "property/feebill/carBillDetail";
    }

    /**
     * @Description 获取业主所有车量账单信息
     * @param model
     * @param req
     * @param resp
     * @param carNo车牌号
     * @return
     */
    @RequestMapping(value = "getCarWithProperty", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson getCarWithProperty(Model model, HttpServletRequest req,
            HttpServletResponse resp, String carNo) {
        RequestJson result = new RequestJson();
        try {
            CarBillDetail carBillDetail = carBillDetailService
                    .getCarWithProperty(carNo);
            if (carBillDetail != null) {
                Integer state = carBillDetail.getState();
                if (state == 0) {
                    carBillDetail.setPayStateString("缴费成功");
                } else if (state == 1) {
                    carBillDetail.setPayStateString("已缴费未同步");
                } else if (state == 2) {
                    carBillDetail.setPayStateString("预缴费");
                } else {
                    carBillDetail.setPayStateString("已删除");
                }

                SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日");
                if (carBillDetail.getEndDate() != null) {
                    String endDateString = formatter.format(carBillDetail
                            .getEndDate());
                    carBillDetail.setEndDateString(endDateString);
                }
                result.setSuccess(true);
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("数据获取成功！");
                result.setObj(carBillDetail);
            } else {
                result.setSuccess(false);
                result.setResultCode(OwnerConstants.RESULT_CODE_FALSE);
                result.setMsg("无数据！");
            }
        } catch (Exception e) {
            result.setSuccess(false);
            result.setResultCode(OwnerConstants.GET_USERINFO_FALSE);
            result.setMsg("网络异常");
        }

        return result;
    }
    
    /**
     * @description 返回车辆添加页面
     * @author chenxin
     * @date 2016年8月16日下午6:31:06
     */
    @RequestMapping(value = "selectPk", method = RequestMethod.GET)
    public String selectPk(Model model, HttpServletRequest req) {
        User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        String userID = user.getId();

        // 获取业主房屋信息
        List<CellHouse> houses = cellHouseService.getListByOwnerIdAndState(userID, OwnerConstants.NORMAL_HOUSE_STATE);

        model.addAttribute("houses", houses);
        return "property/feebill/editCar";
    }

    /**
     * @description 添加车辆
     * @author chenxin
     * @date 2016年8月16日下午4:39:23
     */
    @RequestMapping(value = "saveOrUpdate", method = RequestMethod.GET)
    @ResponseBody
    public RequestJson saveOrUpdate(Model model, String houseId, String carNo, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {

            // 检查车辆的车牌号在“海量数据库”中是否存在，如果存在才能绑定
//            SoapParamsVO vo = InvokeHkWebserviceApi.requestInteface(InvokeHkWebserviceApi.METHOD_NAME_VEHICLE, carNo);
//            if(!vo.isSuccess()) {
//                result.setSuccess(false);
//                result.setMsg(vo.getErrorMessage());
//                return result;
//            }
            

            // 检查车辆是否是 ：存在&&状态--绑定
            CarBill carBillBinding = carBillService.selectByBindingCarNo(carNo);
            if (null != carBillBinding) {
                result.setSuccess(false);
                result.setMsg("车辆已经绑定，不要重复绑定！");
                return result;
            }
            // 检查车辆是否是 ：存在&&状态--解绑
            CarBill carBillUnbunding = carBillService.selectByUnbundingCarNo(carNo);
            if (null != carBillUnbunding && carBillUnbunding.getHouseId() == houseId) {
                carBillUnbunding.setUpdateTime(DateUtils.getDate());
                carBillUnbunding.setState(Constants.STATE_ENABLED);
                carBillService.updateByPrimaryKey(carBillUnbunding);
                result.setSuccess(true);
                result.setMsg("车辆已经绑定，更新状态成功！");
                return result;
            }

            User user = (User) req.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
            String ownerId = user.getId();
            CellInfo cellInfo = user.getCurrentCell();
            String cellId = cellInfo.getId();

            CarBill carBill = new CarBill();
            carBill.setId(UniqueNumberUtils.get18UniqueNumber());
            carBill.setCellId(cellId);
            carBill.setHouseId(houseId);
            carBill.setCarNo(carNo);
            carBill.setOwnerId(ownerId);
            carBill.setCarType(Constants.SELECT_NONE);
            carBill.setGenerateWay(generatedByOwner);
            carBill.setUserAccount(user.getLoginname());
            carBill.setSendTime(DateUtils.getDate());
            carBill.setState(Constants.STATE_ENABLED);

            carBillService.insert(carBill);
            result.setSuccess(true);
            result.setMsg("操作成功！");
        } catch (Exception e) {
            result.setSuccess(false);
            result.setMsg("操作异常！");
        }
        return result;
    }
    
    /**
     * @description 车辆解除绑定
     * @author chenxin
     * @date 2016年8月16日下午4:47:31
     */
    @RequestMapping(value = "deleteCar", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson deleteCar(@RequestParam("carIds[]") String[] carIds, HttpServletRequest req) {

        RequestJson result = new RequestJson();

        try {
            for (String id : carIds) {
                CarBill carBill = new CarBill();
                carBill.setCarNo(id);
                carBill.setState(Constants.STATE_DISABLED);
                carBill.setUpdateTime(DateUtils.getDate());
                carBillService.updateStateByCarNo(carBill);
            }
            result.setSuccess(true);
        } catch (NumberFormatException e) {
            result.setSuccess(false);
            result.setMsg("操作失败");
        }
        return result;
    }
    

    /**
     * @description 检验此小区是否具有缴纳停车费的权限
     * @param cellId 小区id
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingCarRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId();
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if(StringUtils.equals(value, "owner.car")) {
                model.addAttribute("displayCar", Constants.STATE_ENABLED);
            }  
        }
    }
    
    /**
     * @description 检验此小区是否具有缴纳物业费的权限     
     * @param cellId 小区id                 
     * @author chenxin
     * @date 2016年8月31日下午6:54:39
     */
    public void checkingPropertyRightByCellId(HttpServletRequest request, Model model) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        CellInfo cellInfo = user.getCurrentCell();
        String cellId = cellInfo.getId(); 
        
        List<String> list = cellInfoService.getMenusByCellId(cellId, Constants.SYSTEM_OWNER);
        
        for (String item : list) {
            Menu menu = menuService.getMenuById(item);
            String value = menu.getValue();
            if (StringUtils.equals(value, "owner.propertyFee")) {
                model.addAttribute("displayFeeBill", Constants.STATE_ENABLED);
            }
        }
    }
    
    /**
     * 生成预交费账单
     * @Method: saveCarBill
     * @param houseId 房屋信息
     * @param carBillId 车辆信息id
     * @param months 缴费月数
     * @author hubing
     */
    @RequestMapping(value = "saveCarBill", method = RequestMethod.POST)
    @ResponseBody
    public RequestJson saveCarBill(HttpServletRequest request, String houseId, String carBillId,
            Integer months, String billTitle) {
        User user = (User)request.getSession().getAttribute(RequestConstants.USER_SESSION_ID);
        RequestJson result = new RequestJson();
        try {
            // 查询当前房屋物业费状态，欠费下提示不能缴费
            FeeBillDetail lastFeeBillDetail = feeBillDetailService.selectLastBill(houseId);
            long days = DateUtils.getDays(lastFeeBillDetail.getEndDate());
            if(days < 0) {
                result.setSuccess(false);
                result.setMsg("请先缴纳物业费");
            } else {
                String carNo = carBillService.selectByPrimaryKey(carBillId).getCarNo();
                // 查询车辆到期时间
                String endTime = "";
//                SoapParamsVO vo = InvokeHkWebserviceApi.requestInteface(InvokeHkWebserviceApi.METHOD_NAME_VEHICLE, carNo);
//                if(!vo.isSuccess()) {
//                    result.setSuccess(false);
//                    result.setMsg(vo.getErrorMessage());
//                    return result;
//                } else {
//                    endTime = vo.getExpirationTime();
//                }
                
                // 查询缴费单价
                BigDecimal price = BigDecimal.ZERO;
//                vo = InvokeHkWebserviceApi.requestInteface(InvokeHkWebserviceApi.METHOD_NAME_PRICE, carNo);
//                if(!vo.isSuccess()) {
//                    result.setSuccess(false);
//                    result.setMsg(vo.getErrorMessage());
//                    return result;
//                } else {
//                    price = new BigDecimal(vo.getPrice()).divide(new BigDecimal(100), 2, BigDecimal.ROUND_HALF_UP);
//                }
                if(StringUtil.isEmptyString(endTime)) {
                    endTime = DateUtils.formatDate();
                }
                if(BigDecimal.ZERO == price) {
                    price = new BigDecimal(200);
                }
                Date startDate = DateUtils.calDate(DateUtils.stringToDate(endTime), 1);
                Date endDate = DateUtils.calMonthDate(startDate, months);
                
                CarBillDetail detail = new CarBillDetail();
                detail.setId(UniqueNumberUtils.get18UniqueNumber());
                detail.setCarId(carBillId);
                detail.setCarNo(carNo);
                detail.setStartDate(startDate);
                detail.setEndDate(endDate);
                detail.setMonth(months);
                detail.setUnitPrice(price);
                detail.setMoney(price.multiply(new BigDecimal(months)));
                detail.setState(Constants.CAR_PRE_PAY);
                detail.setGenerateWay(Constants.GENERATE_WAY_PRE);
                detail.setOperator(user.getUsername());
                detail.setOperatorAccount(user.getLoginname());
                detail.setOperatorType(Constants.OPERATOR_TYPE_PROPREITOR);
                detail.setCreateTime(new Date());
                if(StringUtil.isEmptyString(billTitle)) {
                    detail.setBillType(Constants.BILL_TYPE_NONE); 
                } else {
                    detail.setBillType(Constants.BILL_TYPE_PERL); 
                    detail.setBillTitle(billTitle);
                }
                
                carBillDetailService.insert(detail);
                
                result.setObj(detail.getId());
                result.setResultCode(OwnerConstants.RESULT_CODE_SUCCESS);
                result.setMsg("数据获取成功！");
            }
            
        } catch (Exception e) {
            e.printStackTrace();
            result.setSuccess(false);
            result.setMsg("系统异常");
        }
        return result;
    }
    
    @RequestMapping(value = "payCarBill", method = RequestMethod.GET)
    public String payCarBill(Model model, String billId, HttpServletRequest request) {

        // 根据房屋id查询账单详情
        CarBillDetail carBillDetail = carBillDetailService.selectByPrimaryKey(billId);
        model.addAttribute("carBillDetail", carBillDetail);
        return "property/feebill/pay_bill";
    }
}
